import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_state.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/group/group_services.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/avatar.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_base.dart';
import 'package:tencent_im_base/tencent_im_base.dart';

typedef GroupApplicationItemBuilder = Widget Function(
    BuildContext context, V2TimGroupApplication applicationInfo, int index);

enum ApplicationStatus {
  none,
  accept,
  reject,
}

class TIMUIKitGroupApplicationList extends StatefulWidget {
  /// the builder for the request item
  final GroupApplicationItemBuilder? itemBuilder;

  /// group ID
  final String groupID;

  const TIMUIKitGroupApplicationList({Key? key, this.itemBuilder, required this.groupID}) : super(key: key);

  @override
  State<StatefulWidget> createState() => TIMUIKitGroupApplicationListState();
}

class TIMUIKitGroupApplicationListState extends TIMUIKitState<TIMUIKitGroupApplicationList> {
  final TUIChatGlobalModel model = serviceLocator<TUIChatGlobalModel>();
  final GroupServices _groupServices = serviceLocator<GroupServices>();
  List<V2TimGroupApplication> groupApplicationList = [];
  List<ApplicationStatus> applicationStatusList = [];

  @override
  void initState() {
    super.initState();
    groupApplicationList = model.groupApplicationList.where((item) => (item.groupID == widget.groupID)).toList();
    applicationStatusList = groupApplicationList.map((item) => ApplicationStatus.none).toList();
  }

  GroupApplicationItemBuilder _getItemBuilder() {
    return widget.itemBuilder ?? _defaultItemBuilder;
  }

  Widget _defaultItemBuilder(BuildContext context, V2TimGroupApplication applicationInfo, int index) {
    final ApplicationStatus currentStatus = applicationStatusList[index];

    String _getUserName() {
      if (applicationInfo.fromUserNickName != null &&
          applicationInfo.fromUserNickName!.isNotEmpty &&
          applicationInfo.fromUserNickName != applicationInfo.fromUser) {
        return "${applicationInfo.fromUserNickName}";
      } else {
        return "";
      }
    }

    return Container(
      padding: const EdgeInsets.all(13),
      margin: const EdgeInsets.only(bottom: 10),
      height: 71,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            height: 45,
            width: 45,
            child: Avatar(
              faceUrl: applicationInfo.fromUserFaceUrl ?? "",
              showName: applicationInfo.fromUserNickName ?? applicationInfo.fromUser ?? "",
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              _getUserName(),
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w400,
                color: Color(0xFF1D2541),
              ),
            ),
          ),
          if (currentStatus == ApplicationStatus.none && applicationInfo.handleStatus == 0)
            InkWell(
              child: Container(
                width: 54,
                height: 26,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(7),
                  color: const Color(0xFFF7F8FA),
                ),
                alignment: Alignment.center,
                child: const Text(
                  "拒绝", // reject
                  style: TextStyle(
                    color: Color(0xFF1D2541),
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              onTap: () async {
                final res = await _groupServices.refuseGroupApplication(
                    addTime: applicationInfo.addTime!,
                    groupID: applicationInfo.groupID,
                    fromUser: applicationInfo.fromUser!,
                    toUser: applicationInfo.toUser!,
                    type: GroupApplicationTypeEnum.values[applicationInfo.type]);
                if (res.code == 0) {
                  setState(() {
                    applicationStatusList[index] = ApplicationStatus.reject;
                  });
                  Future.delayed(const Duration(seconds: 1), () {
                    model.refreshGroupApplicationList();
                  });
                }
              },
            ),
          const SizedBox(width: 10),
          if (currentStatus == ApplicationStatus.none && applicationInfo.handleStatus == 0)
            InkWell(
              child: Container(
                width: 54,
                height: 26,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(7),
                  color: const Color(0xFF0E5AD3),
                ),
                alignment: Alignment.center,
                child: const Text(
                  "同意", // reject
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              onTap: () async {
                final res = await _groupServices.acceptGroupApplication(
                  groupID: applicationInfo.groupID,
                  fromUser: applicationInfo.fromUser!,
                  toUser: applicationInfo.toUser!,
                  type: applicationInfo.type,
                  addTime: applicationInfo.addTime ?? 0,
                );
                if (res.code == 0) {
                  setState(() {
                    applicationStatusList[index] = ApplicationStatus.accept;
                  });
                  Future.delayed(const Duration(seconds: 1), () {
                    model.refreshGroupApplicationList();
                  });
                }
              },
            ),
          if (currentStatus == ApplicationStatus.accept || applicationInfo.handleStatus == 1)
            Container(
              width: 54,
              height: 26,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(7),
                color: const Color(0xFFF7F8FA),
              ),
              alignment: Alignment.center,
              child: const Text(
                "已同意", // reject
                style: TextStyle(
                  color: Color(0xFF7C8191),
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          if (currentStatus == ApplicationStatus.reject || applicationInfo.handleStatus == 2)
            Container(
              width: 54,
              height: 26,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(7),
                color: const Color(0xFFF7F8FA),
              ),
              alignment: Alignment.center,
              child: const Text(
                "已拒绝", // reject
                style: TextStyle(
                  color: Color(0xFF7C8191),
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
        ],
      ),
    );
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    return MultiProvider(
      providers: [ChangeNotifierProvider.value(value: model)],
      builder: (context, w) {
        return ListView.builder(
          itemCount: groupApplicationList.length,
          padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 10),
          itemBuilder: (context, index) {
            final applicationInfo = groupApplicationList[index];
            final itemBuilder = _getItemBuilder();
            return itemBuilder(context, applicationInfo, index);
          },
        );
      },
    );
  }
}
